/**
 * AI智能建议功能Bug测试用例
 * 测试问题：
 * 1. 前端用户ID写死为default_user
 * 2. 后端重复任务类型处理逻辑问题
 * 3. 时间计算混乱（创建时间、截止时间、当前时间）
 */

const API_BASE_URL = 'http://localhost:3001/api'

// 测试数据
const testUsers = [
  {
    id: 'test_user_1',
    email: 'test1@example.com',
    username: 'testuser1'
  },
  {
    id: 'test_user_2', 
    email: 'test2@example.com',
    username: 'testuser2'
  }
]

const testTasks = [
  {
    id: 'task_1',
    userId: 'test_user_1',
    title: '完成项目报告',
    priority: 'P1',
    category: 'work',
    completed: false,
    dueDate: '2024-01-15T10:00:00Z',
    createdAt: '2024-01-10T09:00:00Z',
    isRecurring: false
  },
  {
    id: 'task_2',
    userId: 'test_user_1', 
    title: '每日晨练',
    priority: 'P2',
    category: 'health',
    completed: false,
    dueDate: '2024-01-12T07:00:00Z',
    createdAt: '2024-01-08T08:00:00Z',
    isRecurring: true,
    recurringType: 'daily'
  },
  {
    id: 'task_3',
    userId: 'test_user_2',
    title: '学习新技能',
    priority: 'P2', 
    category: 'learning',
    completed: true,
    dueDate: '2024-01-11T18:00:00Z',
    createdAt: '2024-01-05T10:00:00Z',
    isRecurring: false
  }
]

// 模拟认证token
const mockTokens = {
  'test_user_1': 'mock_token_user_1',
  'test_user_2': 'mock_token_user_2'
}

class AISuggestionsBugTester {
  constructor() {
    this.testResults = []
    this.currentUser = null
  }

  // 记录测试结果
  recordTest(testName, status, details, expected, actual) {
    this.testResults.push({
      testName,
      status, // 'PASS', 'FAIL', 'ERROR'
      details,
      expected,
      actual,
      timestamp: new Date().toISOString()
    })
  }

  // 模拟API请求
  async mockApiRequest(endpoint, options = {}) {
    const url = `${API_BASE_URL}${endpoint}`
    const token = this.currentUser ? mockTokens[this.currentUser.id] : null
    
    console.log(`🔍 测试请求: ${endpoint}`)
    console.log(`👤 当前用户: ${this.currentUser?.id || '未设置'}`)
    console.log(`🔑 使用Token: ${token ? '是' : '否'}`)
    
    // 模拟请求头
    const headers = {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` }),
      ...options.headers,
    }
    
    // 模拟响应
    return {
      url,
      headers,
      method: options.method || 'GET',
      body: options.body
    }
  }

  // 测试1: 前端用户ID写死问题
  async testUserIDHardcodedIssue() {
    console.log('\n🧪 测试1: 前端用户ID写死问题')
    
    try {
      // 模拟不同用户登录
      for (const user of testUsers) {
        this.currentUser = user
        console.log(`\n测试用户: ${user.id}`)
        
        // 模拟前端调用AI建议API
        const request = await this.mockApiRequest('/ai/personalized-suggestions', {
          method: 'POST',
          body: JSON.stringify({
            context: `任务: 完成项目报告`
          })
        })
        
        // 检查请求头中的Authorization
        const hasAuth = request.headers['Authorization'] !== undefined
        const tokenMatches = request.headers['Authorization'] === `Bearer ${mockTokens[user.id]}`
        
        if (hasAuth && tokenMatches) {
          this.recordTest(
            `用户ID认证测试 - ${user.id}`,
            'PASS',
            '用户认证信息正确传递',
            `Bearer ${mockTokens[user.id]}`,
            request.headers['Authorization']
          )
        } else {
          this.recordTest(
            `用户ID认证测试 - ${user.id}`,
            'FAIL', 
            '用户认证信息传递错误',
            `Bearer ${mockTokens[user.id]}`,
            request.headers['Authorization']
          )
        }
      }
      
      // 测试前端代码中是否硬编码了default_user
      const frontendCodeIssue = {
        issue: '前端TaskDetailPage.tsx第904行硬编码了default_user',
        location: 'frontend/src/pages/TaskDetailPage.tsx:904',
        code: "const result = await aiAPI.getPersonalizedSuggestions('default_user', `任务: ${task.title}`)",
        impact: '所有用户都会使用default_user身份获取建议，导致建议不个性化'
      }
      
      this.recordTest(
        '前端硬编码用户ID检查',
        'FAIL',
        '发现硬编码的default_user',
        '使用当前登录用户ID',
        '硬编码为default_user'
      )
      
    } catch (error) {
      this.recordTest(
        '用户ID认证测试',
        'ERROR',
        '测试执行出错',
        '正常执行',
        error.message
      )
    }
  }

  // 测试2: 重复任务处理逻辑问题
  async testRecurringTaskLogic() {
    console.log('\n🧪 测试2: 重复任务处理逻辑问题')
    
    try {
      this.currentUser = testUsers[0] // 使用test_user_1
      
      // 模拟后端获取任务数据的查询
      const mockTasksQuery = `
        SELECT id, title, priority, category, completed, created_at, updated_at
        FROM tasks
        WHERE user_id = $1
        ORDER BY created_at DESC
        LIMIT 30
      `
      
      console.log('📊 模拟任务数据查询:')
      console.log('SQL:', mockTasksQuery)
      console.log('参数:', [this.currentUser.id])
      
      // 模拟查询结果
      const mockTasks = testTasks.filter(task => task.userId === this.currentUser.id)
      console.log('查询结果:', mockTasks)
      
      // 检查是否包含重复任务信息
      const hasRecurringInfo = mockTasks.some(task => 
        task.isRecurring !== undefined && task.recurringType !== undefined
      )
      
      if (!hasRecurringInfo) {
        this.recordTest(
          '重复任务信息查询',
          'FAIL',
          '查询结果缺少重复任务相关信息',
          '包含isRecurring和recurringType字段',
          '缺少重复任务字段'
        )
      } else {
        this.recordTest(
          '重复任务信息查询',
          'PASS',
          '查询结果包含重复任务信息',
          '包含isRecurring和recurringType字段',
          '包含重复任务字段'
        )
      }
      
      // 测试AI建议生成时的重复任务处理
      const recurringTasks = mockTasks.filter(task => task.isRecurring)
      const regularTasks = mockTasks.filter(task => !task.isRecurring)
      
      console.log(`\n📋 任务分类结果:`)
      console.log(`重复任务: ${recurringTasks.length}个`)
      console.log(`普通任务: ${regularTasks.length}个`)
      
      // 检查是否会导致AI建议错误
      if (recurringTasks.length > 0 && regularTasks.length > 0) {
        const potentialIssue = 'AI可能建议合并不同类型的任务'
        this.recordTest(
          '重复任务建议逻辑',
          'FAIL',
          potentialIssue,
          '区分处理重复任务和普通任务',
          '可能混淆任务类型'
        )
      }
      
    } catch (error) {
      this.recordTest(
        '重复任务处理测试',
        'ERROR',
        '测试执行出错',
        '正常执行',
        error.message
      )
    }
  }

  // 测试3: 时间计算混乱问题
  async testTimeCalculationIssues() {
    console.log('\n🧪 测试3: 时间计算混乱问题')
    
    try {
      this.currentUser = testUsers[0]
      
      // 模拟当前时间
      const currentTime = new Date('2024-01-12T15:30:00Z')
      console.log(`🕐 当前时间: ${currentTime.toISOString()}`)
      
      // 分析测试任务的时间信息
      const taskTimeAnalysis = testTasks.map(task => {
        const createdAt = new Date(task.createdAt)
        const dueDate = new Date(task.dueDate)
        const currentTime = new Date('2024-01-12T15:30:00Z')
        
        return {
          taskId: task.id,
          title: task.title,
          createdAt: createdAt.toISOString(),
          dueDate: dueDate.toISOString(),
          currentTime: currentTime.toISOString(),
          timeToDue: Math.round((dueDate - currentTime) / (1000 * 60 * 60)), // 小时
          timeSinceCreated: Math.round((currentTime - createdAt) / (1000 * 60 * 60)), // 小时
          isOverdue: dueDate < currentTime,
          isRecurring: task.isRecurring
        }
      })
      
      console.log('\n📊 时间分析结果:')
      taskTimeAnalysis.forEach(analysis => {
        console.log(`\n任务: ${analysis.title}`)
        console.log(`  创建时间: ${analysis.createdAt}`)
        console.log(`  截止时间: ${analysis.dueDate}`)
        console.log(`  距离截止: ${analysis.timeToDue}小时`)
        console.log(`  创建至今: ${analysis.timeSinceCreated}小时`)
        console.log(`  是否过期: ${analysis.isOverdue ? '是' : '否'}`)
        console.log(`  是否重复: ${analysis.isRecurring ? '是' : '否'}`)
      })
      
      // 检查时间计算问题
      const timeIssues = []
      
      // 检查过期任务
      const overdueTasks = taskTimeAnalysis.filter(t => t.isOverdue)
      if (overdueTasks.length > 0) {
        timeIssues.push(`发现${overdueTasks.length}个过期任务`)
      }
      
      // 检查重复任务的时间处理
      const recurringTasks = taskTimeAnalysis.filter(t => t.isRecurring)
      if (recurringTasks.length > 0) {
        timeIssues.push(`重复任务时间计算可能有问题`)
      }
      
      // 检查时间跨度异常的任务
      const abnormalTasks = taskTimeAnalysis.filter(t => 
        t.timeSinceCreated > 24 * 7 || t.timeToDue < -24
      )
      if (abnormalTasks.length > 0) {
        timeIssues.push(`发现时间跨度异常的任务`)
      }
      
      if (timeIssues.length > 0) {
        this.recordTest(
          '时间计算问题检查',
          'FAIL',
          timeIssues.join('; '),
          '时间计算准确',
          timeIssues.join('; ')
        )
      } else {
        this.recordTest(
          '时间计算问题检查',
          'PASS',
          '时间计算正常',
          '时间计算准确',
          '无时间计算问题'
        )
      }
      
      // 测试AI建议生成时的时间上下文
      const timeContextTest = {
        currentTime: currentTime.toISOString(),
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        workingHours: '09:00-18:00',
        weekend: currentTime.getDay() === 0 || currentTime.getDay() === 6
      }
      
      console.log('\n🕐 时间上下文信息:')
      console.log(JSON.stringify(timeContextTest, null, 2))
      
      // 检查时间上下文是否会影响AI建议
      const contextIssues = []
      if (timeContextTest.weekend) {
        contextIssues.push('当前是周末，AI建议可能不准确')
      }
      if (currentTime.getHours() < 9 || currentTime.getHours() > 18) {
        contextIssues.push('当前是非工作时间，建议可能不适用')
      }
      
      if (contextIssues.length > 0) {
        this.recordTest(
          '时间上下文检查',
          'FAIL',
          contextIssues.join('; '),
          '时间上下文准确',
          contextIssues.join('; ')
        )
      } else {
        this.recordTest(
          '时间上下文检查',
          'PASS',
          '时间上下文正常',
          '时间上下文准确',
          '无时间上下文问题'
        )
      }
      
    } catch (error) {
      this.recordTest(
        '时间计算测试',
        'ERROR',
        '测试执行出错',
        '正常执行',
        error.message
      )
    }
  }

  // 测试4: AI建议生成逻辑问题
  async testAISuggestionGeneration() {
    console.log('\n🧪 测试4: AI建议生成逻辑问题')
    
    try {
      this.currentUser = testUsers[0]
      
      // 模拟AI建议生成的输入数据
      const mockTasks = testTasks.filter(task => task.userId === this.currentUser.id)
      const mockContext = `任务: 完成项目报告`
      
      console.log('📝 AI建议生成输入:')
      console.log('任务数据:', mockTasks)
      console.log('上下文:', mockContext)
      
      // 分析可能导致AI建议错误的问题
      const issues = []
      
      // 1. 检查任务数据完整性
      const incompleteTasks = mockTasks.filter(task => 
        !task.title || !task.priority || !task.category
      )
      if (incompleteTasks.length > 0) {
        issues.push(`发现${incompleteTasks.length}个不完整的任务数据`)
      }
      
      // 2. 检查重复任务和普通任务混合
      const hasRecurring = mockTasks.some(task => task.isRecurring)
      const hasRegular = mockTasks.some(task => !task.isRecurring)
      if (hasRecurring && hasRegular) {
        issues.push('重复任务和普通任务混合，可能导致AI建议混乱')
      }
      
      // 3. 检查时间信息一致性
      const timeInconsistentTasks = mockTasks.filter(task => {
        const createdAt = new Date(task.createdAt)
        const dueDate = new Date(task.dueDate)
        return createdAt > dueDate
      })
      if (timeInconsistentTasks.length > 0) {
        issues.push(`发现${timeInconsistentTasks.length}个时间不一致的任务`)
      }
      
      // 4. 检查用户上下文
      if (mockContext.includes('default_user')) {
        issues.push('上下文包含硬编码的default_user')
      }
      
      if (issues.length > 0) {
        this.recordTest(
          'AI建议生成逻辑检查',
          'FAIL',
          issues.join('; '),
          'AI建议生成逻辑正确',
          issues.join('; ')
        )
      } else {
        this.recordTest(
          'AI建议生成逻辑检查',
          'PASS',
          'AI建议生成逻辑正常',
          'AI建议生成逻辑正确',
          '无逻辑问题'
        )
      }
      
      // 模拟AI建议输出
      const mockSuggestions = [
        {
          type: 'priority_adjustment',
          message: '建议提升任务优先级',
          actions: [{ label: '提升优先级', action: 'elevate_priority', primary: true }],
          reasoning: '基于任务紧急程度分析'
        },
        {
          type: 'time_management',
          message: '建议调整任务时间安排',
          actions: [{ label: '调整时间', action: 'adjust_time', primary: false }],
          reasoning: '基于当前时间分析'
        }
      ]
      
      console.log('\n🤖 模拟AI建议输出:')
      console.log(JSON.stringify(mockSuggestions, null, 2))
      
      // 检查建议质量
      const suggestionIssues = []
      mockSuggestions.forEach((suggestion, index) => {
        if (!suggestion.message || !suggestion.actions || suggestion.actions.length === 0) {
          suggestionIssues.push(`建议${index + 1}格式不完整`)
        }
        if (!suggestion.reasoning) {
          suggestionIssues.push(`建议${index + 1}缺少推理过程`)
        }
      })
      
      if (suggestionIssues.length > 0) {
        this.recordTest(
          'AI建议质量检查',
          'FAIL',
          suggestionIssues.join('; '),
          'AI建议格式完整',
          suggestionIssues.join('; ')
        )
      } else {
        this.recordTest(
          'AI建议质量检查',
          'PASS',
          'AI建议格式完整',
          'AI建议格式完整',
          '建议格式正确'
        )
      }
      
    } catch (error) {
      this.recordTest(
        'AI建议生成测试',
        'ERROR',
        '测试执行出错',
        '正常执行',
        error.message
      )
    }
  }

  // 运行所有测试
  async runAllTests() {
    console.log('🚀 开始AI智能建议功能Bug测试')
    console.log('=' * 60)
    
    await this.testUserIDHardcodedIssue()
    await this.testRecurringTaskLogic()
    await this.testTimeCalculationIssues()
    await this.testAISuggestionGeneration()
    
    this.generateTestReport()
  }

  // 生成测试报告
  generateTestReport() {
    console.log('\n📊 测试报告')
    console.log('=' * 60)
    
    const totalTests = this.testResults.length
    const passedTests = this.testResults.filter(r => r.status === 'PASS').length
    const failedTests = this.testResults.filter(r => r.status === 'FAIL').length
    const errorTests = this.testResults.filter(r => r.status === 'ERROR').length
    
    console.log(`\n📈 测试统计:`)
    console.log(`总测试数: ${totalTests}`)
    console.log(`通过: ${passedTests} (${((passedTests/totalTests)*100).toFixed(1)}%)`)
    console.log(`失败: ${failedTests} (${((failedTests/totalTests)*100).toFixed(1)}%)`)
    console.log(`错误: ${errorTests} (${((errorTests/totalTests)*100).toFixed(1)}%)`)
    
    console.log(`\n📋 详细结果:`)
    this.testResults.forEach((result, index) => {
      const statusIcon = result.status === 'PASS' ? '✅' : result.status === 'FAIL' ? '❌' : '⚠️'
      console.log(`\n${index + 1}. ${statusIcon} ${result.testName}`)
      console.log(`   状态: ${result.status}`)
      console.log(`   详情: ${result.details}`)
      if (result.expected && result.actual) {
        console.log(`   期望: ${result.expected}`)
        console.log(`   实际: ${result.actual}`)
      }
      console.log(`   时间: ${result.timestamp}`)
    })
    
    // 问题总结
    const failedResults = this.testResults.filter(r => r.status === 'FAIL')
    if (failedResults.length > 0) {
      console.log(`\n🔍 发现的问题:`)
      failedResults.forEach((result, index) => {
        console.log(`${index + 1}. ${result.testName}: ${result.details}`)
      })
    }
    
    // 修复建议
    console.log(`\n💡 修复建议:`)
    console.log(`1. 修复前端TaskDetailPage.tsx中硬编码的default_user`)
    console.log(`2. 改进后端任务查询，包含重复任务相关信息`)
    console.log(`3. 统一时间处理逻辑，避免时区和格式混乱`)
    console.log(`4. 优化AI建议生成，区分处理重复任务和普通任务`)
    console.log(`5. 增加时间上下文感知，提供更准确的建议`)
    
    return {
      summary: {
        total: totalTests,
        passed: passedTests,
        failed: failedTests,
        errors: errorTests,
        passRate: ((passedTests/totalTests)*100).toFixed(1) + '%'
      },
      results: this.testResults,
      issues: failedResults.map(r => ({
        test: r.testName,
        issue: r.details
      }))
    }
  }
}

// 运行测试
if (require.main === module) {
  const tester = new AISuggestionsBugTester()
  tester.runAllTests().catch(console.error)
}

module.exports = AISuggestionsBugTester
